import React, { useCallback, useState, useMemo, useEffect } from 'react';
import './list.scss';
import checkImg from '@/assets/check.png';
import checkedImg from '@/assets/checkbox_checked.png';
import { bem } from '@/utils';
import { RightOutline } from 'antd-mobile-icons';

export interface ListProps {
    selectType?: 'checkbox' | 'radio';
    bgColor?: string;
    isSelectOpen?: boolean;
    children?: React.ReactNode;
    headTitle?: string;
    onSelected?: (v: {id: string | number, selected: boolean}) => void;
    onRightClick?: (id?: number | string) => void;
}

export interface ListItemProps {
    id?: number | string;
    left?: React.ReactNode;
    style?: React.CSSProperties | undefined;
    bgColor?: string;
    children?: React.ReactNode;
    right?: React.ReactNode;
    isChecked?: boolean;
    checkbox?: boolean;
    onRightClick?: (id?: number | string) => void;
    onHandlerClick?: (id?: number | string) => void;
}

const defaultProps = {
    checkbox: false,
    selectType: 'radio',
    isSelectOpen: false,
    bgColor: '#fff',
}

export const ListItem: React.FC<ListItemProps> = (props) => {
    const {
        id,
        style,
        left,
        right,
        checkbox,
        children,
        isChecked,
        bgColor,
        onRightClick,
        onHandlerClick,
        ...rest
    } = {
        ...defaultProps,
        ...props
    };

    const getLeft = useMemo(() => {
        if (left) return left;
        if (checkbox) {
            return (
                <div className="seal-list-item__checkbox">
                    <img
                        src={isChecked ? checkedImg : checkImg}
                        alt={isChecked ? "Checked" : "Unchecked"}
                    />
                </div>
            );
        }
        return left;
    }, [left, checkbox, isChecked]);


    return (
        <div className="seal-list-item" style={{background: bgColor, ...style}} onClick={() => {
            onHandlerClick?.(id)
        }}>
            {
                getLeft && (
                    <div className="seal-list-item__left">{getLeft}</div>
                )
            }
            <div className="seal-list-item__content">{children}</div>
            <div className="seal-list-item__right" onClick={() => { onRightClick }}>
                {right ? right : <RightOutline />}
            </div>
        </div>
    );
};

const ListView: React.FC<ListProps> & { Item: typeof ListItem } = (props) => {
    const {
        bgColor,
        isSelectOpen,
        selectType,
        headTitle,
        children,
        onSelected,
        onRightClick,
    } =
    {
        ...defaultProps,
        ...props
    };
    const b = bem('list');

    const childArray = React.Children.toArray(children);

    const initialMap = () => {
        const newMap = new Map();
        childArray?.map((child, i) => {
            if (!React.isValidElement(child)) {
                return;
            }
            const id = child.props?.id || i;
            const isChecked = child.props?.isChecked || false;
            newMap.set(id, isChecked);
        });
        return newMap;
    }

    const [checkedState, setCheckedState] = useState<Map<string | number, boolean>>(initialMap);
    const [checkLock, setCheckLock] = useState<boolean>(false);



    // 更新选中状态的函数
    const updateChecked = useCallback((prev: Map<string | number, boolean>, key: string | number) => {
        if (!isSelectOpen) return prev;
        const newMap = new Map(prev);
        if (selectType === 'checkbox') {
            // 多选模式：切换当前选项状态
            const currentValue = newMap.get(key) || false;
            newMap.set(key, !currentValue);
        } else {
            // 单选模式
            const currentValue = newMap.get(key) || false;

            if (currentValue) {
                // 如果当前已选中，则取消选中
                newMap.set(key, false);
            } else {
                // 如果当前未选中，则选中它并取消其他所有选项
                newMap.forEach((_, k) => newMap.set(k, false));
                newMap.set(key, true);
            }
        }
        return newMap;
    }, [isSelectOpen, selectType]);

    const handlerCheckbox = (id: number | string) => {
        if (checkLock) {
            return;
        }
        setCheckLock(true);

        try {
            if (isSelectOpen) {
                const newMap = updateChecked(checkedState, id);
                setCheckedState(newMap);
                const selected = getChecked(id, newMap);
                onSelected?.({
                    id,
                    selected
                });
            }
        } finally {
            setCheckLock(false);
        }
    };

    const getChecked = useCallback((key: number | string, state: Map<string | number, boolean>) => {
        return state?.get(key) || false;
    }, [checkedState]);

    const handlerRight = (id: number | string) => {
        onRightClick?.(id);
    };

    useEffect(() => {

    }, []);

    return (
        <div className={b()} >
            {headTitle && <div className="seal-list-head">{headTitle}</div>}
            <div className="seal-list-main">
                {
                    childArray.map((child, i) => {
                        if (!React.isValidElement(child)) {
                            return null;
                        }
                        const childProps = child.props;
                        if (!childProps) {
                            return;
                        }
                        const id = childProps?.id || i;
                        return (
                            <ListItem
                                key={id}
                                id={id}
                                style={childProps.style}
                                left={childProps.left}
                                children={childProps.children}
                                right={childProps.right}
                                checkbox={isSelectOpen}
                                bgColor={bgColor}
                                isChecked={getChecked(id, checkedState)}
                                onRightClick={() => { handlerRight(id) }}
                                onHandlerClick={() => {
                                    childProps.onHandlerClick ? childProps.onHandlerClick() : handlerCheckbox(id)
                                }}

                            />

                        )
                    })
                }
            </div>
        </div>
    )
}

ListView.Item = ListView;

export default ListView;